import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    // 创建一个 DatagramSocket 对象, 后续操作网卡的基础
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        //这么写就是手动指定端口
        socket = new DatagramSocket(port);

        //这么写就是让系统自动分配端口
//        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        //通过这个方法来启动服务器
        System.out.println("服务器启动");

        while(true)
        {
            //1. 读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);

            //当前完成 receive 之后, 数据时异 二进制 的行师存储到 DatagramPacket
            //想要能够把数据显示出来需要把这个二进制数据转换成字符串
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            //2. 根据请求计算响应
            String response = process(request);

            //3. 把响应写回到客户端, 搞一个响应对象 DatagramPacket , 往 DatagramPacket 里构造刚才的数据, 再通过send返回
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(responsePacket);

            //4. 打印一个日志, 把这次数据交互的详情打印出来
            System.out.printf("[%s:%d] req=%s, resp=%s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    public String process(String request)
    {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
